<template>
  <el-form :model="form" ref="form" :rules="rules" label-width="120px">
    <el-row :gutter="16">
      <el-col :span="12">
        <el-form-item label="是否发送短信">
          <el-radio-group size="small" @change="handleSmsChange" v-model="form.smsFlag">
            <el-radio-button :label="1">是</el-radio-button>
            <el-radio-button :label="0">否</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item class="check-form-item" label="数据级别" prop="dataMode" size="small">
          <el-checkbox-group v-model="checkList">
            <el-checkbox-button :disabled="true" :label="1">公共级</el-checkbox-button>
            <el-checkbox-button :label="2">部门级</el-checkbox-button>
            <el-checkbox-button :label="3">人员级</el-checkbox-button>
          </el-checkbox-group>
        </el-form-item>
      </el-col>
      <el-col>
        <el-tabs v-model="activeName" @tab-click="handleTabClick">
          <el-tab-pane label="公共" name="first">
            <el-col v-show="form.smsFlag === 1">
              <el-form-item label="短信模板">
                <el-select clearable v-model="smsTemplateId1" style="width: 98%" placeholder="请选择">
                  <el-option
                    v-for="item in templateData"
                    :key="item.smsTemplateId"
                    :value="item.smsTemplateId"
                    :label="item.smsTemplateContent"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="信息模板">
                <el-input
                  style="width: 98%"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入内容"
                  v-model="messageTemplate1"
                />
                <p
                  class="mb0 color-999"
                >变量使用${var + 字段名}，与数据字段名匹配。特殊变量：${runTime}运行时间，${total}预警总数，${ruleName}ruleName预警规则名称</p>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="通知人设置">
                <el-button
                  class="mb10"
                  type="primary"
                  @click="handleAddColumn('commonData')"
                  icon="el-icon-plus"
                />
                <report-table
                  @tableUpdate="arr => handleNoticeUpdate(arr, 'common')"
                  :tableData="commonData"
                  type="common"
                  ref="noticeTable"
                />
              </el-form-item>
            </el-col>
            <el-col v-show="warningGrade === 3">
              <el-form-item label="上报设置">
                <el-button
                  class="mb10"
                  type="primary"
                  @click="handleAddColumn('reportData')"
                  icon="el-icon-plus"
                />
                <report-table
                  @tableUpdate="arr => handleNoticeUpdate(arr, 'report')"
                  :tableData="reportData"
                  type="report"
                  ref="noticeTable"
                />
              </el-form-item>
            </el-col>
          </el-tab-pane>
          <el-tab-pane v-if="showTabPane(2)" label="部门" name="second">
            <el-col>
              <el-form-item label="部门字段" prop="deptField">
                <el-select clearable style="width: 98%" v-model="form.deptField">
                  <el-option
                    v-for="(item,index) in repeatData"
                    :key="index"
                    :value="item"
                    :label="item"
                  />
                </el-select>
                <!-- <el-input style="width: 98%" v-model="form.deptField" placeholder="请输入" /> -->
              </el-form-item>
            </el-col>
            <el-col v-show="form.smsFlag === 1">
              <el-form-item label="短信模板">
                <el-select clearable v-model="smsTemplateId2" style="width: 98%" placeholder="请选择">
                  <el-option
                    v-for="item in templateData"
                    :key="item.smsTemplateId"
                    :value="item.smsTemplateId"
                    :label="item.smsTemplateContent"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="信息模板">
                <el-input
                  style="width: 98%"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入内容"
                  v-model="messageTemplate2"
                />
                <p
                  class="mb0 color-999"
                >变量使用${var + 字段名}，与数据字段名匹配。特殊变量：${runTime}运行时间，${total}预警总数，${ruleName}ruleName预警规则名称</p>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="部门通知人设置">
                <el-button
                  class="mb10"
                  type="primary"
                  @click="handleAddColumn('deptData')"
                  icon="el-icon-plus"
                />
                <dept-table @tableUpdate="handleDeptUpdate" :tableData="deptData" ref="deptTable" />
              </el-form-item>
            </el-col>
          </el-tab-pane>
          <el-tab-pane v-if="showTabPane(3)" label="人员" name="third">
            <el-col>
              <el-form-item label="用户字段" prop="userField">
                <el-select clearable style="width: 98%" v-model="form.userField">
                  <el-option
                    v-for="(item,index) in repeatData"
                    :key="index"
                    :value="item"
                    :label="item"
                  />
                </el-select>
                <!-- <el-input style="width: 98%" v-model="form.userField" placeholder="请输入" /> -->
              </el-form-item>
            </el-col>
            <el-col v-show="form.smsFlag === 1">
              <el-form-item label="短信模板">
                <el-select clearable v-model="smsTemplateId3" style="width: 98%" placeholder="请选择">
                  <el-option
                    v-for="item in templateData"
                    :key="item.smsTemplateId"
                    :value="item.smsTemplateId"
                    :label="item.smsTemplateContent"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="信息模板">
                <el-input
                  style="width: 98%"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入内容"
                  v-model="messageTemplate3"
                />
                <p
                  class="mb0 color-999"
                >变量使用${var + 字段名}，与数据字段名匹配。特殊变量：${runTime}运行时间，${total}预警总数，${ruleName}ruleName预警规则名称</p>
              </el-form-item>
            </el-col>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
  </el-form>
</template>

<script>
import DeptTable from './DeptTable'
import NoticeTable from './NoticeTable'
import ReportTable from './ReportTable'
import { getWarningTemplate } from '@/api/prewarning'

export default {
  components: {
    ReportTable,
    DeptTable,
    NoticeTable
  },
  data() {
    return {
      checkList: [1],
      activeName: 'first',
      form: {},
      smsTemplateId1: null,
      smsTemplateId2: null,
      smsTemplateId3: null,
      messageTemplate1: null,
      messageTemplate2: null,
      messageTemplate3: null,
      rules: {
        deptField: [{ required: true, message: '请填写部门字段', trigger: 'blur' }],
        userField: [{ required: true, message: '请填写用户字段', trigger: 'blur' }]
      },
      loading: false,
      commonData: [],
      deptData: [],
      reportData: [], // 上报数据
      warningGrade: null, // 预警等级
      templateData: [],
      // dynamicTags: [],
      // inputVisible: false,
      // inputValue: null,
      repeatData: []
    }
  },
  watch: {
    checkList: {
      handler(n, o) {
        // console.log('n', n)
        if (n.length < o.length) {
          this.activeName = 'first'
        }
      }
    }
  },
  computed: {
    showTabPane() {
      return function(str) {
        let showPane = false
        this.checkList.map(v => {
          if (v === str) {
            showPane = true
          }
        })
        return this.checkList.length > 1 && showPane
      }
    }
  },
  mounted() {
    getWarningTemplate().then(res => {
      console.log('template res', res)
      this.templateData = res.data
    })
  },
  methods: {
    setRepeatData(arr) {
      this.repeatData = [...arr]
    },
    reset() {
      this.form = Object.assign({}, {})
      this.commonData = []
      this.deptData = []
      this.reportData = []
      this.checkList = [1]
      this.dynamicTags = []
      for (let i = 1; i < 4; i++) {
        this[`${'messageTemplate' + i}`] = null
      }
    },
    edit(obj, obj2) {
      console.log('obj', obj)
      // 部门字段和用户字段在obj2里面
      const { deptField, userField } = obj2
      this.$set(this.form, 'deptField', deptField)
      this.$set(this.form, 'userField', userField)

      // tab栏回显
      this.checkList = []
      obj.messages.map((v, i) => {
        if (v.smsTemplateId) {
          this.form.smsFlag = 1
        }
        this.checkList.push(v.dataMode)
        this[`${'smsTemplateId' + Number(i + 1)}`] = v.smsTemplateId
        this[`${'messageTemplate' + Number(i + 1)}`] = v.messageTemplate
      })
      // 通知人表格数据回显
      let commonArr = []
      obj.notifiers.map((v, ind) => {
        commonArr.push({
          xmId: ind + 1,
          ...v,
          ruleId: v.ruleId
        })
      })
      this.commonData = [...commonArr]

      // 上报表格数据回显
      let reportArr = []
      obj.warningReporteds.map((v, ind) => {
        reportArr.push({
          xmId: ind + 1,
          ...v,
          ruleId: v.ruleId
        })
      })
      console.log('reportArr', reportArr)

      this.reportData = [...reportArr]

      // 部门通知人表格数据回显
      let deptReportData = []
      obj.notifierDepts.map((v, ind) => {
        deptReportData.push({
          xmId: ind + 1,
          dataDeptId: v.dataDeptId,
          notifierDeptId: v.notifierDeptId,
          notifierPositionId: v.notifierDeptId + '-' + v.notifierPositionId,
          ruleId: v.ruleId
        })
      })

      this.deptData = [...deptReportData]
    },
    handleSmsChange(e) {
      console.log('e', e)
      if (e === 0) {
        this.smsTemplateId1 = null
        this.smsTemplateId2 = null
        this.smsTemplateId3 = null
      }
    },
    handleTabClick() {},
    // 传递数据
    postData() {
      let message = []
      this.checkList.map((v, i) => {
        message.push({
          dataMode: v,
          smsTemplateId: this[`${'smsTemplateId' + Number(i + 1)}`],
          messageTemplate: this[`${'messageTemplate' + Number(i + 1)}`]
        })
      })

      this.$set(this.form, 'message', message)
      let manPass = true,
        deptPass = true,
        deptManPass = true
      // if (this.form.smsFlag) {
      // 发送短信才需要添加通知人
      if (this.commonData.length > 0) {
        manPass = this.commonData.every(v => v.notifierUserId || v.notifierRoleId || v.notifierPositionId || v.notifierDeptId)
        this.$set(this.form, 'notifier', this.commonData)
      } else {
        this.$message.error('请添加一条通知人记录')
        manPass = false
      }
      // }

      if (this.warningGrade === 3) {
        if (this.reportData.length > 0) {
          this.$set(this.form, 'report', this.reportData)
        } else {
          this.$message.error('请添加一条上报记录')
          deptPass = false
        }
      }

      let dept = this.checkList.some(v => v === 2)
      if (dept) {
        if (this.deptData.length > 0) {
          deptManPass = this.deptData.every(v => v.dataDeptId && v.notifierDeptId && v.notifierPositionId && v.thresholdValue)
          if (!deptManPass) {
            this.$message.error('部门级部门通知人设置数据未填写完整')
          }
          this.deptData.map(v => {
            v.smsTemplateId = this.smsTemplateId2
            v.messageTemplate = this.messageTemplate2
          })
          this.$set(this.form, 'notifierDept', this.deptData)
        } else {
          this.$message.error('请添加一条部门通知人记录')
          deptManPass = false
        }
      }

      console.log('notice', manPass, deptPass, deptManPass, this.form)
      if (manPass && deptPass && deptManPass) {
        this.$emit('noticeData', this.form)
      } else {
        if (!manPass) {
          this.$message.error('公共通知人填写数据有问题')
        }
        if (!deptPass) {
          this.$message.error('上报设置填写数据有问题')
        }
        if (!deptManPass) {
          this.$message.error('部门通知人填写数据有问题')
        }
        this.$emit('notSubmit', 'notice')
      }
    },
    handleDeptUpdate(arr) {
      this.deptData = [...arr]
    },
    handleNoticeUpdate(arr, type) {
      if (type === 'report') {
        this.reportData = [...arr]
      } else {
        this.commonData = [...arr]
        console.log('commonData', this.commonData)
      }
    },
    // 新增行
    handleAddColumn(str) {
      this[`${str}`].push({
        xmId: this[`${str}`].length + 1
      })
    },
    // index 传递过来预警等级的变化值
    gradeChange(num) {
      this.warningGrade = num
    }
  }
}
</script>

<style scoped>
.check-form-item >>> .el-checkbox-button.is-disabled:first-child .el-checkbox-button__inner {
  color: #fff;
  background-color: #409eff;
  border-color: #409eff;
  -webkit-box-shadow: -1px 0 0 0 #8cc5ff;
  box-shadow: -1px 0 0 0 #8cc5ff;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
